package com.shiro;

import com.common.ShiroExceptionUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DelegatingSubject;
import org.apache.shiro.util.Assert;
import org.apache.shiro.util.Factory;

import java.util.Scanner;

public class LoginUtil {

    public static void main(String[] args) {
        new LoginUtil().login("zhang","123");
    }

    public void login(String username,String password){

        Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro-realm.ini");
        DefaultSecurityManager securityManager= (DefaultSecurityManager) factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        Subject subject=SecurityUtils.getSubject();
        try{
            subject.login(token);
        }catch (Exception e){
            ShiroExceptionUtil.getShiroExceptionUtil().savereason(e);
        }

        System.out.println(securityManager.getClass());
        System.out.println(subject.getClass());
        Assert.isTrue(subject.isAuthenticated());

        DelegatingSubject sub= (DelegatingSubject) subject;
        System.out.println(sub.isAuthenticated());

//        subject.logout();
        Scanner scanner=new Scanner(System.in);
        scanner.next();
    }
}
